public without sharing class IntentProductController {
   

  public Boolean isErr {get;set;}
  public String  msg {get;set;}
  public Boolean isSuccess {get;set;}

  public String  paramJson {get;set;}
  public String searchJson {get;set;}

  public String saveJson {get;set;}

  public String cate1combox {get;set;}
  public String cate2combox {get;set;}
  public String cate3combox {get;set;}
  public String purposecombox {get;set;}

  public String plantypecombox {get;set;}

  public String aplicableInstrumentcombbox{get;private set;}

  public String  cooptypeJson {get;set;}
  public String  deptJson {get;set;}
  public String sealflag ;
  public String oppId {get;set;}
  public User u ;
  public Boolean isCouldFindOverseaProduct;

  public Boolean isDealer {get;private set;}

  private Opportunity opp ;  


    public void init(){
      setNil();
        oppId =System.currentPageReference().getParameters().get('oppid');
        if(oppId == null)setErr('页面打开错误!');
        u = [select Id ,Profile.Name ,SubCompany__c from User where Id=:UserInfo.getUserId()];
         opp = [select AccountId,RecordType.DeveloperName ,StageName from Opportunity where Id=: oppId ];
         
         if(opp.StageName == '合同签订' || opp.StageName == '失败' )setErr('业务机会'+opp.StageName +'阶段不能操作!');
         
        isDealer = opp.RecordType.DeveloperName == 'DealerOpportunity';

        isCouldFindOverseaProduct = u.Profile.Name.contains('海外') ? true : false;

        Map<String,String> cm = ImportObject.getPicklistValues('Contract__c','Corpcode__c',false);
        if(cm.get(u.SubCompany__c) == null)setErr('公司编码维护错误!请联系管理员维护!');
        sealflag = 'Y-'+cm.get(u.SubCompany__c);
        deptJson = getOptMap(ImportObject.getPicklistValues('IntentProduct__c', 'HospitalDepartments__c', true));
        cooptypeJson = getOptMap(ImportObject.getPicklistValues('IntentProduct__c','CoopType__c',true));
        cate1combox = getOptsFromLabel(Label.Product_Category1);
        cate2combox = getOptsFromLabel(Label.Product_Category2);
        cate3combox = getOptsFromLabel(Label.Product_Category3);
        purposecombox = getOptsFromLabel(Label.Product_Purpose);
        aplicableInstrumentcombbox = getOptMap(ImportObject.getPicklistValues('Product__c', 'ApplicableInstrumentModel__c', true));
        plantypecombox = getOptMap(ImportObject.getPicklistValues('PlannedUseProjects__c', 'Type__c', true));
    }
    public String getOptsFromLabel(String lb){
        Map<String,String> tmpMap = new Map<String,String>();

        tmpMap.put('', System.Label.Option_None);
        for (String str : lb.split(',', -1)) {
            tmpMap.put(str, str);
        }
        return getOptMap(tmpMap);
    }
  ///置空参数
    public void setNil(){ 
      paramJson = '';
      searchJson = '';
      deptJson = '';
      cooptypeJson = '';
      cate1combox = '';
      cate2combox = '';
      cate3combox = '';
      purposecombox = '';
      saveJson = '';

    }
    public String getOptMap(Map<String,String> opts){
       Map<String ,Object> cooMap = new Map<String ,Object> ();
      cooMap.put('valueField', 'value');
      cooMap.put('textField', 'label');
      cooMap.put('panelHeight', 'auto');
      cooMap.put('limitToList', 'true');
      List<Map<String,String>>  dList = new List<Map<String,String>>();
      for (String k : opts.keySet()) {
        Map<String ,String> dataMap = new Map<String,String>();
        dataMap.put('label',opts.get(k) );
        dataMap.put('value',k );
        dList.add(dataMap);
      }  
      cooMap.put('data', dList);   
      
      return EncodingUtil.urlEncode(JSON.serialize(cooMap), 'UTF-8');
    }

   public void setErr(String message){
      isErr = true;
      ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,message));
    }

    public void getRegent(){

      getIntentProducts(false);

    }
    public void getEquipment(){
      getIntentProducts(true);
    }
    public void getIntentProducts(Boolean isEuip){
      //coopType
      String sql = 'select Id,Product__r.ProductName__c,Product__r.NCinvshortname__c,Product__r.Name,Product__r.Unit__c ,Product__r.Brand__c,Product__r.Spec__c ,Product__r.Model__c ,Product__r.SerialNo__c,CompetitorProduct__c,Product__c, Product__r.ApplicableInstrumentModel__c,';
       sql += 'TerminalClient__c,TerminalClient__r.Name , Product__r.MatchingInstrument__c, Quantity__c,SampleAmount__c,HospitalDepartments__c,CompetitorBrand__c,CoopType__c,CompetitorCompany__c from IntentProduct__c where Opportunity__c = \''+oppId+'\'';
      
      if(isEuip){
        sql += ' and (Product__r.Category0__c  in ' + Label.EuipmentCategory0 +'  OR  Product__r.MatchingInstrument__c != null ) ';
      }else{
        sql += ' and Product__r.Category0__c not in ' + Label.EuipmentCategory0 + ' and  Product__r.MatchingInstrument__c = null  ';
      }



      System.debug(sql);
      List<ProductBean> tmp = new List<ProductBean>();
      Set<String>  pids = new Set<String>();
      List<IntentProduct__c> ipList = Database.query(sql);
      Map<Id,Map<String, PlanProjectBean>>mkpMap = getPlanProjects();

      for(IntentProduct__c ip : ipList){
          pids.add(ip.Product__c);
      }

      Map<Id,List<PlanProjectBean>>mkproductMap  = getMkProjects(pids);
       for(IntentProduct__c ip :ipList ){
          
         List<PlanProjectBean> mkpL  =  mkproductMap.get(ip.Product__c);
        System.debug('IntentProductControllerPlans==>'+ mkpL);

         if(mkpMap.containsKey(ip.Id) && mkpL != null ){
            for(PlanProjectBean ppb : mkpL){
                if(mkpMap.get(ip.Id).containsKey(ppb.planprojectId)){
                    ppb.plannum = mkpMap.get(ip.Id).get(ppb.planprojectId).plannum;
                    ppb.plantype = mkpMap.get(ip.Id).get(ppb.planprojectId).plantype;
                }
            }
         }
          tmp.add(new ProductBean(ip,isEuip,isDealer,opp,isEuip ? mkpL : null  ));
      }

      System.debug(tmp);

      searchJson = EncodingUtil.urlEncode(JSON.serialize(tmp),'UTF-8');

    }

    //获取意向产品的计划项目
    public  Map<Id,Map<String, PlanProjectBean>>  getPlanProjects(){
        
        Map<Id,Map<String,PlanProjectBean>> mkPjs = new Map<Id,Map<String,PlanProjectBean>>();
        
        for (PlannedUseProjects__c mp  : [select Id,IntentionalProduct__r.Product__c,IntentionalProduct__c , 
          Type__c,MaccuraProject__c,MaccuraProject__r.Name ,SpecimenVolume__c  from PlannedUseProjects__c where IntentionalProduct__r.Opportunity__c =: oppid ]) {
          
          Map<String,PlanProjectBean> mkL = mkPjs.containsKey(mp.IntentionalProduct__c) ? mkPjs.get(mp.IntentionalProduct__c) : new Map<String,PlanProjectBean>();
          mkL.put(mp.MaccuraProject__c,new PlanProjectBean(mp));
          mkPjs.put(mp.IntentionalProduct__c ,mkL);
        }
        return mkPjs;

    }
    //获取产品的迈克项目
    public  Map<Id,List<PlanProjectBean>>  getMkProjects(Set<String >pids ){
        Map<Id,List<PlanProjectBean>> mkPjs = new Map<Id,List<PlanProjectBean>>();
        for (MaccuraProject__c mp  : [select Name , MatchingInstrument__c from MaccuraProject__c where MatchingInstrument__c in:pids]) {
        
          List<PlanProjectBean>  mkL = mkPjs.containsKey(mp.MatchingInstrument__c) ? mkPjs.get(mp.MatchingInstrument__c) : new List<PlanProjectBean>();
          mkL.add(new PlanProjectBean(mp));
          mkPjs.put(mp.MatchingInstrument__c ,mkL);
        }
        return mkPjs;

    }
    public void search(){
      System.debug(paramJson);
      Map<String,Object> searchMap =(Map<String,Object> )JSON.deserializeUntyped(EncodingUtil.urlDecode(paramJson, 'UTF-8'));
      String sql = 'select Id,ProductName__c,MatchingInstrument__c ,Name ,Unit__c, Brand__c,Spec__c,Model__c,SerialNo__c ,SealCompany__c ,NCCode__c,Category1__c,Category2__c,Category0__c,NCinvshortname__c,ApplicableInstrumentModel__c  from Product__c where Name != null ';
      
        sql +=  (isCouldFindOverseaProduct ?  ' and (Overseasproducts__c  = true  or Brand__c in '+MaccuraBrandUtil.getMaccuraInStr()+ ') ':  ' and  Overseasproducts__c != true  ' );

      String relatedSql = sql ; 

      if(String.isBlank(String.valueOf(searchMap.get('name'))) == false)sql += ' and ProductName__c like \'%'+String.valueOf(searchMap.get('name'))+'%\'';
      
      if(String.isBlank(String.valueOf(searchMap.get('brand'))) == false)sql += ' and Brand__c like \'%'+String.valueOf(searchMap.get('brand'))+'%\'';
      
      if(String.isBlank(String.valueOf(searchMap.get('serialno'))) == false)sql += ' and SerialNo__c like \'%'+String.valueOf(searchMap.get('serialno'))+'%\'';
      
      if(String.isBlank(String.valueOf(searchMap.get('model'))) == false)sql += ' and Model__c like \'%'+String.valueOf(searchMap.get('model'))+'%\'';
      
      if(String.isBlank(String.valueOf(searchMap.get('nccode'))) == false)sql += ' and NCCode__c like \'%'+String.valueOf(searchMap.get('nccode'))+'%\'';
      
      if(String.isBlank(String.valueOf(searchMap.get('cate1'))) == false)sql += ' and Category1__c like \'%'+String.valueOf(searchMap.get('cate1'))+'%\'';
      
      if(String.isBlank(String.valueOf(searchMap.get('cate2'))) == false)sql += ' and Category2__c like \'%'+String.valueOf(searchMap.get('cate2'))+'%\'';
      
      if(String.isBlank(String.valueOf(searchMap.get('cate3'))) == false)sql += ' and Category3__c like \'%'+String.valueOf(searchMap.get('cate3'))+'%\'';
      
      if(String.isBlank(String.valueOf(searchMap.get('purpose'))) == false)sql += ' and Purpose__c like \'%'+String.valueOf(searchMap.get('purpose'))+'%\'';

      if(String.isBlank(String.valueOf(searchMap.get('application'))) == false)sql += ' and ApplicableInstrumentModel__c includes (\''+String.valueOf(searchMap.get('application'))+'\') ';

      Boolean isEuip = Boolean.valueOf(searchMap.get('isEuip'));
      if(isEuip  ){
        sql += ' and Category0__c  in  '+ Label.EuipmentCategory0 ;
      }else{
        sql += ' and Category0__c not in  ' + Label.EuipmentCategory0;
      }

      sql += '  Limit 300 ';




      Map<String,Object> resMap = new  Map<String,Object>();
      List<ProductBean> tmp = new List<ProductBean>();
      Set<String> equips = new Set<String>();
      List<Product__c> pList = (List<Product__c>)SQLUtil.query(sql);
      for(Product__c p :pList ){

          if(isEuip)equips.add(p.Id);
        
      }



      Map<Id,List<PlanProjectBean>>mkpMap = getMkProjects(equips);
      for(Product__c p : pList){
        if(!(p.SealCompany__c != null && p.SealCompany__c.contains(sealflag))){
          tmp.add(new ProductBean(p,isEuip,isDealer,opp, isEuip ? mkpMap.get(p.Id ) : new List<PlanProjectBean>() ));
        }
      }
      resMap.put('data', tmp);
      System.debug('IntentProductController==>'+resMap);
      /*if(isEuip){
        if(equips.size() == 0) return;
        relatedSql += ' and MatchingInstrument__c in ' + transStr(equips);
        Map<String,List<ProductBean>> relatedMap = new Map<String,List<ProductBean>>();
              System.debug('IntentProductController==>'+relatedSql);

        for(Product__c p : Database.query(relatedSql)){
          if(!(p.SealCompany__c != null && p.SealCompany__c.contains(sealflag))){
              List<ProductBean> pl = new List<ProductBean>();
              if(relatedMap.containsKey(p.MatchingInstrument__c))pl.addAll(relatedMap.get(p.MatchingInstrument__c));
              pl.add(new ProductBean(p,isEuip,isDealer,opp,new List<PlanProjectBean>()));
              relatedMap.put(p.MatchingInstrument__c,pl);

          }
        }
        resMap.put('related',relatedMap);
      }*/
      //System.debug('IntentProductController==>'+resMap);
      searchJson = EncodingUtil.urlEncode(JSON.serialize(resMap),'UTF-8');

    }

    
    private String transStr (Set<String> nset){
      if(nset == null || nset.size()== 0)return '()';
      String s = JSON.serialize(nset);
        s = s.replaceAll('"','\'');
      s = s.replace('[','(');
      s = s.replace(']',')');
      return s;

    }
    public void save(){
      msg = '';
      List<Object> resList=(List<Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));
      System.debug('IntentProductControllerSave==>'+ resList);
      List<IntentProduct__c>   tList = new List<IntentProduct__c>();

      Map<String,List<PlannedUseProjects__c>> planMap = new Map<String,List<PlannedUseProjects__c>>();
      Map<String,String> prodMap = new Map<String,String>();
      for (Object res : resList) {
        Map<String ,Object> o = (Map<String ,Object> )res;
        IntentProduct__c ip = new IntentProduct__c();
        String productId = getIdValue(o.get('productId'));

        if(productId == null){
          msg = String.valueOf(o.get('name'))+'  数据异常!';
          break;
        }


        ip.Product__c = productId;
        ip.CompetitorProduct__c = String.valueOf(o.get('competitorProduct'));
        ip.Quantity__c = getDecimalValue(o.get('num'));

        ip.SampleAmount__c = getDecimalValue(o.get('daynum'));
        ip.CoopType__c = String.valueOf(o.get('coopType'));
        ip.HospitalDepartments__c = String.valueOf(o.get('tardept'));
        ip.CompetitorBrand__c = String.valueOf(o.get('competitorBrand'));
        ip.CompetitorCompany__c = String.valueOf(o.get('competitorCompany'));
        ip.CompetitorProduct__c = String.valueOf(o.get('competitorModel'));

        ip.Brand__c = String.valueOf(o.get('brand'));
        ip.Spec__c = String.valueOf(o.get('spec'));
        ip.SerialNo__c = String.valueOf(o.get('serialno'));
        ip.Model__c = String.valueOf(o.get('model'));
        ip.TerminalClient__c = getIdValue(o.get('terminalId'));

        prodMap.put(ip.Product__c +'-'+ip.TerminalClient__c, ip.Product__c);
        System.debug('IntentProductControllerPlans==>'+ o.get('plans'));

        if(o.get('plans') != null ){

            List<Object> plans = (List<Object>)o.get('plans');
            if(plans.size() > 0){
                List<PlannedUseProjects__c> planList = new List<PlannedUseProjects__c>();
                
                for(Object planO  : plans ){
                    Map<String,Object > planMo = (Map<String,Object>)planO;
                    PlannedUseProjects__c pp =  new PlannedUseProjects__c();
                    pp.MaccuraProject__c = getIdValue(planMo.get('planprojectId'));
                    pp.SpecimenVolume__c = getDecimalValue(planMo.get('plannum'));
                    pp.Type__c = String.valueOf(planMo.get('plantype'));

                    planList.add(pp);
                }
                 planMap.put( (ip.Product__c +'_'+ ip.TerminalClient__c ), planList);
            }
            

        }

        ip.Opportunity__c = oppId;
        tList.add(ip);
      }

    
      Map<String ,String> errMap = new Map<String,String>();
      //判断 当前 客户 正在进行的业务机会(非当前业务机会) 是否存在 同终端同产品(仪器) 如果存在 则报错 不允许出现
      for(IntentProduct__c ip :Database.query('select Product__r.ProductName__c,Opportunity__c,Opportunity__r.Name,Product__r.NCCode__c ,Product__c ,TerminalClient__c from IntentProduct__c where  Opportunity__r.Is_Stop__c != true and  Opportunity__c != \''+opp.Id+'\' and  Opportunity__r.AccountId = \''+opp.AccountId+'\' and  Opportunity__r.StageName not in (\'合同签订\',\'失败\') and Product__r.Category0__c  in  '+ Label.EuipmentCategory0 )){

          if(prodMap.containsKey(ip.Product__c +'-'+ ip.TerminalClient__c )){
              String key = '<a href="/'+ip.Opportunity__c+'">'+ip.Opportunity__r.Name+'</a>';
              String s = errMap.containsKey(key) ? errMap.get(key)+(ip.Product__r.ProductName__c + ' : '+ip.Product__r.NCCode__c) : (ip.Product__r.ProductName__c + ' : '+ip.Product__r.NCCode__c);
              errMap.put(key,s); 
             // s += ip.Product__r.ProductName__c + ' : '+ip.Product__r.NCCode__c;
          }

      }
      if(errMap.keySet().size() > 0 ){

        Integer i = 1; 
         msg += '当前客户其他进行中的业务机会:';
        for(String k : errMap.keySet()){
          //当前客户其他进行中的业务机会（业务机会1--超链接）存在以下相同的意向产品：
           msg += '<br />'+i + ')'+k +' : ' + errMap.get(k) +' <br/> ';
           i ++ ;



        }
         
      }


      if(msg.length() > 0){

        return;
      }
      SavePoint sp = Database.setSavepoint();
      try {
          List<IntentProduct__c> deleList = [select Id from IntentProduct__c where Opportunity__c =:oppId ];
          if(deleList != null && deleList.size() > 0)delete deleList;
          delete [select Id from PlannedUseProjects__c where IntentionalProduct__r.Opportunity__c =:oppId];


          if(tList.size() > 0) insert tList;
          List<PlannedUseProjects__c> plansL = new List<PlannedUseProjects__c>();
          for (IntentProduct__c ip   :tList  ) {
              if(planMap.containsKey(ip.Product__c +'_'+ ip.TerminalClient__c)){
                  for(PlannedUseProjects__c pp : planMap.get(ip.Product__c +'_'+ ip.TerminalClient__c)){
                    pp.IntentionalProduct__c = ip.Id;
                    plansL.add(pp);
                  }
              }
          }

          if(plansL.size() > 0) insert plansL;

          msg = '保存成功!';
          isSuccess = true;
      }catch (Exception e) {
         Database.rollback(sp);
          msg = '保存失败!'+e.getMessage();

      }

    }

     private String getIdValue(Object val ){
         if(val == null)return null;

        String  d = String.valueOf(val);
        if(d.trim() == '')return null;
        return Id.valueOf(d.trim());
     }
     private Decimal getDecimalValue(Object val){
        if(val == null)return null;

        String  d = String.valueOf(val);
        if(d == '')return null;
        return Decimal.valueOf(d.trim());
    }

    public class PlanProjectBean{

      public String planname ;//项目名称
      public String planproductId ; //产品Id 
      public String planintentId ; //意向产品Id
      public String plantype ;//类型
      public Decimal  plannum ; //日标本量
      public String planprojectId ; //项目Id 

      public PlanProjectBean(MaccuraProject__c mp   ){
          planname  = mp.Name ;
          planproductId = mp.MatchingInstrument__c;
          planprojectId = mp.Id ; 
      }

      public PlanProjectBean(PlannedUseProjects__c pup ){
          planname = pup.MaccuraProject__r.Name ;
          planproductId = pup.IntentionalProduct__r.Product__c;
          planintentId = pup.IntentionalProduct__c;
          plantype = pup.Type__c;
          plannum = pup.SpecimenVolume__c;
          planprojectId = pup.MaccuraProject__c;

      }


    }
    public class ProductBean {
      public String name ;//产品
      public String shortName ;//简称
      public String brand ;//品牌
      public String spec ;//规格
      public String model ;//型号
      public String serialno ;//货号
      public String productId ;
      public String accId ; 

      public String num ;
      public String daynum;
      public String coopType;
      public String tardept;

      public String competitorModel;
      public String competitorBrand;
      public String competitorCompany;


      public Boolean isEuip;
      public String unit ;

      public String nccode;
      public String cate0;
      public String cate1;
      public String cate2;

      public String application;

      public List<PlanProjectBean> mkProjects;//迈克项目

      public String relatedId ;
      public String terminalId;
      public String terminal;

      public ProductBean(IntentProduct__c ip,Boolean isE,Boolean isde,Opportunity opp  ,List<PlanProjectBean> mkpj ){
          name = ip.Product__r.ProductName__c == null ?   ip.Product__r.Name : ip.Product__r.ProductName__c ;
          shortName = ip.Product__r.NCinvshortname__c;
          brand  = ip.Product__r.Brand__c;
          spec = ip.Product__r.Spec__c;
          model = ip.Product__r.Model__c;
          serialno = ip.Product__r.SerialNo__c;

          num = String.valueOf(ip.Quantity__c);
          daynum = String.valueOf(ip.SampleAmount__c);
          coopType = ip.CoopType__c;
          tardept = ip.HospitalDepartments__c;
          unit = ip.Product__r.Unit__c;
          terminalId = isde ?   ip.TerminalClient__c : opp.AccountId;
          if(isde)terminal = ip.TerminalClient__r.Name ;

          competitorModel = ip.CompetitorProduct__c;
          competitorCompany = ip.CompetitorCompany__c;
          competitorBrand = ip.CompetitorBrand__c;
          productId = ip.Product__c;
          mkProjects = mkpj;
          relatedId = ip.Product__r.MatchingInstrument__c;


          application = ip.Product__r.ApplicableInstrumentModel__c;

          isEuip = isE;
      }
      public ProductBean(Product__c p,Boolean isE,Boolean isde,Opportunity opp ,List<PlanProjectBean> mkpj  ){
          name = p.ProductName__c == null ? p.Name : p.ProductName__c ;
           shortName = p.NCinvshortname__c;
          brand  = p.Brand__c;
          spec = p.Spec__c;
          model = p.Model__c;
          serialno = p.SerialNo__c;
          nccode = p.NCCode__c;
          cate0 = p.Category0__c;
          cate1 = p.Category1__c;
          cate2 = p.Category2__c; 
          productId = p.Id;
          unit = p.Unit__c;
          relatedId = p.MatchingInstrument__c;
          application = p.ApplicableInstrumentModel__c;
          isEuip = isE;
          mkProjects = mkpj;
          terminalId = isde ?  '' : opp.AccountId ;
      }
    }
  }

    
/* 
//产品目录
public with sharing class IntentProductController {
   

  public Boolean isErr {get;set;}
  public String  msg {get;set;}
  public Boolean isSuccess {get;set;}

  public String  paramJson {get;set;}
  public String searchJson {get;set;}

  public String saveJson {get;set;}

  public String cate1combox {get;set;}
  public String cate2combox {get;set;}
  public String cate3combox {get;set;}
  public String purposecombox {get;set;}
  public String companycombox {get;set;}
  public String accountlevelcombox {get;set;}


  public String  cooptypeJson {get;set;}
  public String  deptJson {get;set;}
  public String sealflag ;
  public String oppId {get;set;}
  public User u ;
  public Boolean isCouldFindOverseaProduct;
  public Set<String> equipCate ;

  public Map<String,String> companyMap ;


    public void init(){
        setNil();
        equipCate = new Set<String>();
        oppId =System.currentPageReference().getParameters().get('oppid');
        companyMap = new Map<String,String>();
        for(String com : Label.ShortCompanyName.split(',',-1)){
            List<String> cs = com.split('-',-1);
            if(cs != null && cs.size() > 1)companyMap.put(cs[0],cs[1]);
        }

        if(oppId == null)setErr('页面打开错误!');

        u = [select Id ,Profile.Name ,SubCompany__c from User where Id=:UserInfo.getUserId()];

        isCouldFindOverseaProduct = u.Profile.Name.contains('海外') ? true : false;

        Map<String,String> cm = ImportObject.getPicklistValues('Contract__c','Corpcode__c',false);
        if(cm.get(u.SubCompany__c) == null)setErr('公司编码维护错误!请联系管理员维护!');
        sealflag = 'Y-'+cm.get(u.SubCompany__c);
        deptJson = getOptMap(ImportObject.getPicklistValues('IntentProduct__c', 'HospitalDepartments__c', true));
        cooptypeJson = getOptMap(ImportObject.getPicklistValues('IntentProduct__c','CoopType__c',true));
        companycombox = getOptMap(ImportObject.getPicklistValues('User', 'SubCompany__c', true));
        accountlevelcombox = getOptMap(ImportObject.getPicklistValues('Account', 'Level__c', true));

        cate1combox = getOptsFromProduct('Category1__c');
        cate2combox = getOptsFromProduct('Category2__c');
        cate3combox = getOptsFromProduct('Category3__c');
        purposecombox = getOptsFromLabel(Label.Product_Purpose);

        for (Object o  : (List<Object>)JSON.deserializeUntyped(Label.EuipmentCategory0.replaceAll('\'','"').replace('(','[').replace(')',']'))) {
            equipCate.add(String.valueOf(o));
        }
    }
    public String getOptsFromProduct(String cate ){

      Map<String,String> tmpMap = new Map<String,String>();

        for (AggregateResult arg  :Database.query('select '+cate +'  from Product__c group by '+cate ) ){
            tmpMap.put(String.valueOf(arg.get(cate)), String.valueOf(arg.get(cate)));
        }
        return getOptMap(tmpMap);
    }
    public String getOptsFromLabel(String lb ){
        Map<String,String> tmpMap = new Map<String,String>();


        tmpMap.put('', System.Label.Option_None);
        for (String str : lb.split(',', -1)) {
            tmpMap.put(str, str);
        }
        return getOptMap(tmpMap);
    }
  ///置空参数
    public void setNil(){ 
      paramJson = '';
      searchJson = '';
      deptJson = '';
      cooptypeJson = '';
      cate1combox = '';
      cate2combox = '';
      cate3combox = '';
      purposecombox = '';
      saveJson = '';

    }
    public String getOptMap(Map<String,String> opts){
       Map<String ,Object> cooMap = new Map<String ,Object> ();
      cooMap.put('valueField', 'value');
      cooMap.put('textField', 'label');
      cooMap.put('panelHeight', '200');
      cooMap.put('limitToList', 'true');
      List<Map<String,String>>  dList = new List<Map<String,String>>();
      for (String k : opts.keySet()) {
        Map<String ,String> dataMap = new Map<String,String>();
        dataMap.put('label',opts.get(k) );
        dataMap.put('value',k );
        dList.add(dataMap);
      }  
      cooMap.put('data', dList);   
      
      return EncodingUtil.urlEncode(JSON.serialize(cooMap), 'UTF-8');
    }

   public void setErr(String message){
      isErr = true;
      ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,message));
    }

    public void getRegent(){

      getIntentProducts('Regent');

    }
    public void getEquipment(){
      getIntentProducts('Equipment');
    }
    public void getCatalogProduct(){
      getIntentProducts('CatelogProduct');

    }
    public void getIntentProducts(String cate ){

      String sql = 'select Id,Product__r.Name,Product__r.Unit__c ,Product__r.Brand__c,Product__r.Spec__c ,Product__r.Model__c ,Product__r.SerialNo__c,CompetitorProduct__c,Product__c,Product__r.ProductName__c , Product__r.Category0__c , ';

       sql += 'IsFromCatalog__c, Quantity__c,SampleAmount__c,CoopType__c,HospitalDepartments__c,CompetitorBrand__c,CompetitorCompany__c from IntentProduct__c where Opportunity__c = \''+oppId+'\'  ';

       if(cate == 'CatelogProduct'){

           sql += ' and IsFromCatalog__c = true ';

       }else{
        
        sql += ' and IsFromCatalog__c = false  ';

         if(cate == 'Equipment'){

            sql += ' and Product__r.Category0__c  in ' + Label.EuipmentCategory0;

          }else{

            sql += ' and Product__r.Category0__c not in ' + Label.EuipmentCategory0;

          }
      }
     
      System.debug(sql);
      List<ProductBean> tmp = new List<ProductBean>();
      for(IntentProduct__c ip :Database.query(sql)){
          tmp.add(new ProductBean(ip,equipCate));
      }

      searchJson = EncodingUtil.urlEncode(JSON.serialize(tmp),'UTF-8');

    }

    public void searchCatalogProduct( ){
         Map<String,Object> searchMap =(Map<String,Object> )JSON.deserializeUntyped(EncodingUtil.urlDecode(paramJson, 'UTF-8'));

        String sql = ' select Id,Product__r.Name,Product__r.Unit__c ,Product__r.Brand__c,Product__r.Spec__c ,Product__r.Model__c ,Product__r.SerialNo__c,Product__c,Product__r.ProductName__c,  '
        + ' AccountLevel__c,  AuthorizedArea__c ,Company__c,Product__r.NCCode__c,Product__r.Category0__c,Product__r.Category1__c,Product__r.Category2__c,Product__r.Category3__c ,'
        + ' Product__r.SealCompany__c from ProductCatalog__c where Product__c != null  ';

        if(!isCouldFindOverseaProduct) sql += ' and  Product__r.Overseasproducts__c != true  ';

        if(String.isBlank(String.valueOf(searchMap.get('name'))) == false){
          sql += ' and Product__r.ProductName__c like \'%'+String.valueOf(searchMap.get('name'))+'%\'';
        }
        if(String.isBlank(String.valueOf(searchMap.get('brand'))) == false){
          sql += ' and Product__r.Brand__c like \'%'+String.valueOf(searchMap.get('brand'))+'%\'';
        }
        if(String.isBlank(String.valueOf(searchMap.get('serialno'))) == false){
          sql += ' and Product__r.SerialNo__c like \'%'+String.valueOf(searchMap.get('serialno'))+'%\'';
        }
        if(String.isBlank(String.valueOf(searchMap.get('model'))) == false){
         sql += ' and Product__r.Model__c like \'%'+String.valueOf(searchMap.get('model'))+'%\'';
        }
        if(String.isBlank(String.valueOf(searchMap.get('nccode'))) == false){
          sql += ' and Product__r.NCCode__c like \'%'+String.valueOf(searchMap.get('nccode'))+'%\'';
        }
        if(String.isBlank(String.valueOf(searchMap.get('cate1'))) == false){
          sql += ' and Product__r.Category1__c like \'%'+String.valueOf(searchMap.get('cate1'))+'%\'';
        }
        if(String.isBlank(String.valueOf(searchMap.get('cate2'))) == false){
          sql += ' and Product__r.Category2__c like \'%'+String.valueOf(searchMap.get('cate2'))+'%\'';
        }
        if(String.isBlank(String.valueOf(searchMap.get('cate3'))) == false){
          sql += ' and Product__r.Category3__c like \'%'+String.valueOf(searchMap.get('cate3'))+'%\'';
        } 

        if(String.isBlank(String.valueOf(searchMap.get('accountlevel'))) == false){//客户等级
          sql += ' and AccountLevel__c in  (\''+String.valueOf(searchMap.get('accountlevel'))+'\')';
        }
        if(String.isBlank(String.valueOf(searchMap.get('autharea'))) == false){//授权区域
          sql += ' and AuthorizedArea__c like \'%'+String.valueOf(searchMap.get('autharea'))+'%\'';
        }
        if(String.isBlank(String.valueOf(searchMap.get('company'))) == false){//授权区域
          sql += ' and Company__c in  (\''+ companyMap.get(String.valueOf(searchMap.get('company')))+'\')';
        }
       
        sql += '  Limit 300 ';
        System.debug(sql);
        List<ProductBean> tmp = new List<ProductBean>();
        for(ProductCatalog__c p : Database.query(sql)){
          if(!(p.Product__r.SealCompany__c != null && p.Product__r.SealCompany__c.contains(sealflag)))tmp.add(new ProductBean(p,equipCate,companyMap));
        }
        searchJson = EncodingUtil.urlEncode(JSON.serialize(tmp),'UTF-8');


    }

    public void search(){
      System.debug(paramJson);
      Map<String,Object> searchMap =(Map<String,Object> )JSON.deserializeUntyped(EncodingUtil.urlDecode(paramJson, 'UTF-8'));
      String sql = 'select Id ,Name ,ProductName__c ,Unit__c, Brand__c,Spec__c,Model__c,SerialNo__c ,SealCompany__c ,NCCode__c,Category1__c,Category2__c,Category0__c  from Product__c where Name != null ';
      
      if(!isCouldFindOverseaProduct) sql += ' and  Overseasproducts__c != true  ';

      if(String.isBlank(String.valueOf(searchMap.get('name'))) == false){
        sql += ' and ProductName__c like \'%'+String.valueOf(searchMap.get('name'))+'%\'';
      }
      if(String.isBlank(String.valueOf(searchMap.get('brand'))) == false){
        sql += ' and Brand__c like \'%'+String.valueOf(searchMap.get('brand'))+'%\'';
      }
      if(String.isBlank(String.valueOf(searchMap.get('serialno'))) == false){
        sql += ' and SerialNo__c like \'%'+String.valueOf(searchMap.get('serialno'))+'%\'';
      }
      if(String.isBlank(String.valueOf(searchMap.get('model'))) == false){
        sql += ' and Model__c like \'%'+String.valueOf(searchMap.get('model'))+'%\'';
      }
      if(String.isBlank(String.valueOf(searchMap.get('nccode'))) == false){
        sql += ' and NCCode__c like \'%'+String.valueOf(searchMap.get('nccode'))+'%\'';
      }
      if(String.isBlank(String.valueOf(searchMap.get('cate1'))) == false){
        sql += ' and Category1__c like \'%'+String.valueOf(searchMap.get('cate1'))+'%\'';
      }
      if(String.isBlank(String.valueOf(searchMap.get('cate2'))) == false){
        sql += ' and Category2__c like \'%'+String.valueOf(searchMap.get('cate2'))+'%\'';
      }
      if(String.isBlank(String.valueOf(searchMap.get('cate3'))) == false){
        sql += ' and Category3__c like \'%'+String.valueOf(searchMap.get('cate3'))+'%\'';
      }
      if(String.isBlank(String.valueOf(searchMap.get('purpose'))) == false){
        sql += ' and Purpose__c like \'%'+String.valueOf(searchMap.get('purpose'))+'%\'';
      }
      Boolean isEuip = Boolean.valueOf(searchMap.get('isEuip'));

      if(isEuip  ){

        sql += ' and Category0__c  in '  + Label.EuipmentCategory0;

      }else{

        sql += ' and Category0__c not in ' + Label.EuipmentCategory0;

      }

      sql += '  Limit 300 ';
      List<ProductBean> tmp = new List<ProductBean>();
      for(Product__c p : Database.query(sql)){
        if(!(p.SealCompany__c != null && p.SealCompany__c.contains(sealflag)))tmp.add(new ProductBean(p,equipCate));
      }
      searchJson = EncodingUtil.urlEncode(JSON.serialize(tmp),'UTF-8');

    }


    public void save(){
      msg = '';
      List<Object> resList=(List<Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));
      if(resList.size() == 0){
        msg = '保存失败,没有数据!';
        return;
      }
      List<IntentProduct__c>   tList = new List<IntentProduct__c>();
      for (Object res : resList) {
        Map<String ,Object> o = (Map<String ,Object> )res;
        IntentProduct__c ip = new IntentProduct__c();
        String productId = String.valueOf(o.get('productId'));

        if(productId == null){
          msg = String.valueOf(o.get('name'))+'  数据异常!';
          break;
        }
        ip.Product__c = productId;
        ip.CompetitorProduct__c = String.valueOf(o.get('competitorProduct'));
        ip.Quantity__c = getDecimalValue(o.get('num'));

        ip.SampleAmount__c = getDecimalValue(o.get('daynum'));
        ip.CoopType__c = String.valueOf(o.get('coopType'));
        ip.HospitalDepartments__c = String.valueOf(o.get('tardept'));
        ip.CompetitorBrand__c = String.valueOf(o.get('competitorBrand'));
        ip.CompetitorCompany__c = String.valueOf(o.get('competitorCompany'));
        ip.CompetitorProduct__c = String.valueOf(o.get('competitorModel'));

        ip.Brand__c = String.valueOf(o.get('brand'));
        ip.Spec__c = String.valueOf(o.get('spec'));
        ip.SerialNo__c = String.valueOf(o.get('serialno'));
        ip.Model__c = String.valueOf(o.get('model'));
        ip.IsFromCatalog__c =Boolean.valueOf(o.get('isFromCatalog'));
        ip.Opportunity__c = oppId;
        tList.add(ip);
      }

      if(msg.length() > 0){

        return;
      }
      SavePoint sp = Database.setSavepoint();
      try {
          List<IntentProduct__c> deleList = [select Id from IntentProduct__c where Opportunity__c =:oppId ];
          if(deleList != null && deleList.size() > 0)delete deleList;
          if(tList.size() > 0) insert tList;
          msg = '保存成功!';
          isSuccess = true;
      }catch (Exception e) {
         Database.rollback(sp);
          msg = '保存失败!'+e.getMessage();

      }

    }
     private Decimal getDecimalValue(Object val){
        if(val == null)return null;

        String  d = String.valueOf(val);
        if(d == '')return null;
        return Decimal.valueOf(d.trim());
    }
    public class ProductBean {
      public String name ;//产品
      public String brand ;//品牌
      public String spec ;//规格
      public String model ;//型号
      public String serialno ;//货号
      public String productId ; 

      public String num ;
      public String daynum;
      public String coopType;
      public String tardept;

      public String competitorModel;
      public String competitorBrand;
      public String competitorCompany;
      public Boolean isEuip;
      public String unit ;

      public String nccode;
      public String cate0;
      public String cate1;
      public String cate2;

      public String accountlevel;
      public String autharea;
      public String company;


      public Boolean isFromCatalog ; 

      public ProductBean(IntentProduct__c ip,Set<String> ecate){
          name = ip.Product__r.ProductName__c == null ? ip.Product__r.Name : ip.Product__r.ProductName__c ;
          brand  = ip.Product__r.Brand__c;
          spec = ip.Product__r.Spec__c;
          model = ip.Product__r.Model__c;
          serialno = ip.Product__r.SerialNo__c;

          num = String.valueOf(ip.Quantity__c);
          daynum = String.valueOf(ip.SampleAmount__c);
          coopType = ip.CoopType__c;
          tardept = ip.HospitalDepartments__c;
          unit = ip.Product__r.Unit__c;

          competitorModel = ip.CompetitorProduct__c;
          competitorCompany = ip.CompetitorCompany__c;
          competitorBrand = ip.CompetitorBrand__c;
          productId = ip.Product__c;
          isFromCatalog = ip.IsFromCatalog__c; 
           isEuip = ecate.contains(ip.Product__r.Category0__c) ;


         // isEuip = isE;
      }
      public ProductBean(Product__c p,Set<String> ecate){
          name = p.ProductName__c == null ? p.Name : p.ProductName__c ;
          brand  = p.Brand__c;
          spec = p.Spec__c;
          model = p.Model__c;
          serialno = p.SerialNo__c;
          nccode = p.NCCode__c;
          cate0 = p.Category0__c;
          cate1 = p.Category1__c;
          cate2 = p.Category2__c; 
           productId = p.Id;
           unit = p.Unit__c;
          isFromCatalog = false; 
           isEuip = ecate.contains(p.Category0__c) ;

          //isEuip = isE;
      }
      public ProductBean(ProductCatalog__c p,Set<String> ecate,Map<String,String> comMap  ){
          name = p.Product__r.ProductName__c == null ? p.Product__r.Name : p.Product__r.ProductName__c ;
          brand  = p.Product__r.Brand__c;
          spec = p.Product__r.Spec__c;
          model = p.Product__r.Model__c;
          serialno = p.Product__r.SerialNo__c;
          nccode = p.Product__r.NCCode__c;
          cate0 = p.Product__r.Category0__c;
          cate1 = p.Product__r.Category1__c;
          cate2 = p.Product__r.Category2__c; 
           productId = p.Product__c;
           unit = p.Product__r.Unit__c;
           autharea = p.AuthorizedArea__c;
           accountlevel = p.AccountLevel__c;
           isFromCatalog = true; 
           isEuip = ecate.contains(p.Product__r.Category0__c) ;
           company = getCompanystring(p.Company__c,comMap );



          //isEuip = isE;
      }
      private String getCompanystring (String coms ,Map<String,String> companys){
          String c = '';
          if(coms == null) return c;
          for (String cs  :coms.split(';') ) {
            if(companys.containsKey(cs)){
              c += companys.get(cs)+';';
            }
          }
          return c;

      }
      */